<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class ChooseGoods extends Model
{
    protected $autoWriteTimestamp = true;

    public static function goods($currentPage,$perPage){
        $uid = getUid();
        $cs = self::field('id,activity_goods_id,user_id,create_time')->order('create_time','desc')->where(['user_id'=>$uid])->paginate(['page'=>$currentPage,'list_rows'=>$perPage]);
        $goods = [];
        if($cs){
            $cs = $cs->toArray();
            if($cs['data']){
                foreach($cs['data'] as $k=>$v){
                    $goods['data'][] = ActivityGoods::where(['id'=>$v['activity_goods_id']])->find();
                }
            }else{
                $goods['data'] = [];
            }

            $goods['total'] = $cs['total'];
            $goods['per_page'] = $cs['per_page'];
            $goods['current_page'] = $cs['current_page'];
            $goods['last_page'] = $cs['last_page'];
        }else{
            $goods = $cs;
        }
        return $goods;
    }

    public static function choose($gid){
        $uid = getUid();

        if($gid){
            foreach($gid as $v){
                $res = self::where(['user_id'=>$uid,'activity_goods_id'=>$v])->find();
                if(!$res){
                    $d = [
                        'user_id' => $uid,
                        'activity_goods_id' => $v,
                        'create_time' => time(),
                        'update_time' => time()
                    ];
                    self::insert($d);
                }
            }

            return true;
        }

        return false;
    }

    public static function delChoose($gid){
        $uid = getUid();

        if($gid){
            foreach($gid as $v){
                $choose = self::where(['user_id'=>$uid,'activity_goods_id'=>$v])->find();
                if(!$choose || ($uid != $choose->user_id)){
                    return false;
                }

                self::where(['user_id'=>$uid,'activity_goods_id'=>$v])->delete();
            }
            return true;
        }

        return false;
    }
}
